// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.

import * as path from "path";
import * as semver from "semver";
import * as fse from "fs-extra";
import * as lodash from "lodash";
import { commands, Disposable, Extension, ExtensionContext, extensions, QuickPickItem, Uri, window, workspace , WorkspaceFolder} from "vscode";

export class ProjectManager implements Disposable{
 
    dispose() {
        throw new Error("Method not implemented.");
    }
    
    public constructor(public readonly context: ExtensionContext) {      
   }

    public async openProject() {
        const availableCommands: string[] = await commands.getCommands();
        if (availableCommands.includes("workbench.action.files.openFolder")) {
            return commands.executeCommand("workbench.action.files.openFolder");
        }
        return commands.executeCommand("workbench.action.files.openFileFolder");
    }

    public async createProject(triggerFrom : string) {
        const items: IProjectTypeQuickPick[] = projectTypes.map((type: IProjectType) => {
            return {
                label: type.displayName,
                description: type.description,
                detail: type.detail,
                metadata: type.metadata,
            };
        });
        const choice = await window.showQuickPick(items, {
            ignoreFocusOut: true,
            placeHolder: "选择一个工程类型",
        });
        if (!choice || !await ensureExtension(choice.label, choice.metadata)) {
            return;
        }
        if (choice.metadata.type === ProjectType.Android) {
            await scaffoldAndroidProject(this.context);
        } else if(choice.metadata.type === ProjectType.Windows){
            await scaffoldWindowsProject(this.context);
        } else if(choice.metadata.type === ProjectType.webpage){
            await scaffoldWebProject(this.context);
        }
        sendInfo("", {
            projectCreationType: choice.metadata.type,
            triggerfrom: triggerFrom,
        });
    }
}

interface IProjectType {
    displayName: string;
    description?: string;
    detail?: string;
    metadata: IProjectTypeMetadata;
}

interface IProjectTypeMetadata {
    type: ProjectType;
}

interface IProjectTypeQuickPick extends QuickPickItem {
    metadata: IProjectTypeMetadata;
}

async function scaffoldAndroidProject(context: ExtensionContext): Promise<void> {
    const workspaceFolder = getDefaultWorkspaceFolder();
    const location: Uri[] | undefined = await window.showOpenDialog({
        defaultUri: workspaceFolder && workspaceFolder.uri,
        canSelectFiles: false,
        canSelectFolders: true,
        openLabel: "选择一个工程位置",
    });
    if (!location || !location.length) {
        return;
    }

    const basePath: string = location[0].fsPath;
    const projectName: string | undefined = await window.showInputBox({
        prompt: "请输入一个工程名称",
        ignoreFocusOut: true,
        validateInput: async (name: string): Promise<string> => {
            if (name && !name.match(/^[^*~/\\]+$/)) {
                return "请输入一个工程名称";
            }
            if (name && await fse.pathExists(path.join(basePath, name))) {
                return "已存在同名工程";
            }
            return "";
        },
    });

    if (!projectName) {
        return;
    }

    const projectRoot: string = path.join(basePath, projectName);
    const templateRoot: string = path.join(context.extensionPath, "templates", "android-project");
    try {

        await fse.ensureDir(projectRoot);
        await fse.copy(templateRoot, projectRoot);
        await fse.ensureDir(path.join(projectRoot, "绳包"));
    } catch (error) {
        return;
    }
    const openInNewWindow = workspace && !lodash.isEmpty(workspace.workspaceFolders);
    await commands.executeCommand("vscode.openFolder", Uri.file(path.join(basePath, projectName)), openInNewWindow);
}

async function scaffoldWindowsProject(context: ExtensionContext): Promise<void> {
    const workspaceFolder = getDefaultWorkspaceFolder();
    const location: Uri[] | undefined = await window.showOpenDialog({
        defaultUri: workspaceFolder && workspaceFolder.uri,
        canSelectFiles: false,
        canSelectFolders: true,
        openLabel: "选择一个工程位置",
    });
    if (!location || !location.length) {
        return;
    }

    const basePath: string = location[0].fsPath;
    const projectName: string | undefined = await window.showInputBox({
        prompt: "请输入一个工程名称",
        ignoreFocusOut: true,
        validateInput: async (name: string): Promise<string> => {
            if (name && !name.match(/^[^*~/\\]+$/)) {
                return "请输入一个工程名称";
            }
            if (name && await fse.pathExists(path.join(basePath, name))) {
                return "已存在同名工程";
            }
            return "";
        },
    });

    if (!projectName) {
        return;
    }

    const projectRoot: string = path.join(basePath, projectName);
    const templateRoot: string = path.join(context.extensionPath, "templates", "windows-project");
    try {

        await fse.ensureDir(projectRoot);
        await fse.copy(templateRoot, projectRoot);
        await fse.ensureDir(path.join(projectRoot, "绳包"));
    } catch (error) {
        return;
    }
    const openInNewWindow = workspace && !lodash.isEmpty(workspace.workspaceFolders);
    await commands.executeCommand("vscode.openFolder", Uri.file(path.join(basePath, projectName)), openInNewWindow);
}


async function scaffoldWebProject(context: ExtensionContext): Promise<void> {
    const workspaceFolder = getDefaultWorkspaceFolder();
    const location: Uri[] | undefined = await window.showOpenDialog({
        defaultUri: workspaceFolder && workspaceFolder.uri,
        canSelectFiles: false,
        canSelectFolders: true,
        openLabel: "选择一个工程位置",
    });
    if (!location || !location.length) {
        return;
    }

    const basePath: string = location[0].fsPath;
    const projectName: string | undefined = await window.showInputBox({
        prompt: "请输入一个工程名称",
        ignoreFocusOut: true,
        validateInput: async (name: string): Promise<string> => {
            if (name && !name.match(/^[^*~/\\]+$/)) {
                return "请输入一个工程名称";
            }
            if (name && await fse.pathExists(path.join(basePath, name))) {
                return "已存在同名工程";
            }
            return "";
        },
    });

    if (!projectName) {
        return;
    }

    const projectRoot: string = path.join(basePath, projectName);
    const templateRoot: string = path.join(context.extensionPath, "templates", "web-project");
    try {

        await fse.ensureDir(projectRoot);
        await fse.copy(templateRoot, projectRoot);
        await fse.ensureDir(path.join(projectRoot, "绳包"));
    } catch (error) {
        return;
    }
    const openInNewWindow = workspace && !lodash.isEmpty(workspace.workspaceFolders);
    await commands.executeCommand("vscode.openFolder", Uri.file(path.join(basePath, projectName)), openInNewWindow);
}

enum ProjectType {
    Android = "结绳安卓工程",
    Windows= "结绳Windows工程",
    webpage = "结绳网页工程",
}

const projectTypes: IProjectType[] = [
    {
        displayName: "结绳安卓工程",
        detail: "结绳中文安卓项目",
        metadata: {
            type: ProjectType.Android,
        },
    },
    {
        displayName: "结绳Windows工程",
        detail: "结绳中文windows项目",
        metadata: {
            type: ProjectType.Windows,
        },
    },
    {
        displayName: "结绳网页工程",
        detail: "结绳中文web项目",
        metadata: {
            type: ProjectType.webpage,
        },
    },
];



function sendInfo(arg0: string, arg1: { projectCreationType: ProjectType; triggerfrom: string; }) {
    throw new Error("Function not implemented.");
}

async function ensureExtension(typeName: string, metaData: IProjectTypeMetadata): Promise<boolean> {
    if (!metaData.type) {
        return true;
    }
    return true;
}

function getDefaultWorkspaceFolder(): WorkspaceFolder | undefined {
    if (workspace.workspaceFolders === undefined) {
        return undefined;
    }
    if (workspace.workspaceFolders.length === 1) {
        return workspace.workspaceFolders[0];
    }
    if (window.activeTextEditor) {
        const activeWorkspaceFolder: WorkspaceFolder | undefined =
            workspace.getWorkspaceFolder(window.activeTextEditor.document.uri);
        return activeWorkspaceFolder;
    }
    return undefined;
}
